package com.drcoffee.drcoffeemall.util;

import com.drcoffee.drcoffeemall.entry.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.GeneralSecurityException;
import java.util.Date;

public class CreatJwtUtil {
    public static String getoken(User user) throws GeneralSecurityException {
        Jwts.builder();//生成
        Jwts.parser();//解密

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(user.getId() + "")//设置需要加密的内容
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())//token保留时间
                .signWith(SignatureAlgorithm.HS256, "user-token").setExpiration(
                        new Date(new Date().getTime() + 86400000)
                );
        System.out.println(jwtBuilder.compact());
        return jwtBuilder.compact();
    }

    public static User decrypt(String token) throws GeneralSecurityException {
        //调用解密方法
        Claims claims = Jwts.parser()
                .setSigningKey("user-token")
                .parseClaimsJws(token)
                .getBody();

        User user = new User();
        user.setId(Integer.valueOf(claims.getId()));
        user.setUsername(claims.getSubject());
        return user;
    }
}
